<template>
    <div class="user_list_container">
        <ZWSearch
            row-num="3"
            :option="searchOption"
            @search="search"
            @reset="reset"
            @input="inputSearch"
            @expand="expandSearch" />
        <ZWTable
            ref="orderTableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @select-all="onSelectAll"
            @data-change="tableDataChange">
            <template #headerOperateLeft>
                <div style="display: flex; align-items: center">
                    <div style="font-size: 13px; line-height: 1; margin-right: 10px">
                        最近同步时间：{{ updateTime }}
                    </div>
                    <div style="display: flex; align-items: center">
                        <el-dropdown style="margin-left: 10px">
                            <span
                                style="
                                    color: #ff6b00;
                                    font-size: 12px;
                                    cursor: pointer;
                                    line-height: 1;
                                    padding-right: 6px;
                                ">
                                同步店铺用户<el-icon class="el-icon--right"><arrow-down /></el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="synchronousData">
                                        直接同步&nbsp;
                                        <el-tooltip
                                            class="box-item"
                                            effect="dark"
                                            :content="synchronousTips"
                                            placement="top">
                                            <el-image
                                                src="/static/question.png"
                                                style="width: 16px; height: 16px"></el-image>
                                            <!-- <el-icon color="#ccc"><QuestionFilled /></el-icon> -->
                                        </el-tooltip>
                                    </el-dropdown-item>
                                    <el-dropdown-item @click="synchronousProData">
                                        高级同步&nbsp;
                                        <el-tooltip
                                            class="box-item"
                                            effect="dark"
                                            :content="synchronousProTips"
                                            placement="top">
                                            <el-image
                                                src="/static/question.png"
                                                style="width: 16px; height: 16px"></el-image>
                                            <!-- <el-icon color="#ccc"><QuestionFilled /></el-icon> -->
                                        </el-tooltip>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="synchronousUserTips"
                            placement="right-start">
                            <el-image src="/static/question.png" style="width: 16px; height: 16px"></el-image>
                            <!-- <el-icon color="#ccc"><QuestionFilled /></el-icon> -->
                        </el-tooltip>
                    </div>
                    <div
                        v-if="isShowRefresh"
                        style="font-size: 13px; line-height: 1; margin-left: 10px; cursor: pointer; color: #ff6b00"
                        @click="reset">
                        刷新
                    </div>
                </div>
            </template>
            <template #headerOperate>
                <el-button @click="settingPro">高级设置</el-button>
            </template>
        </ZWTable>
    </div>

    <Dialog :app-dialog="appDialogSettingPro">
        <el-form ref="settingProFormRef" :model="settingProForm" :rules="settingProFormRules" label-width="auto">
            <el-form-item label="自动同步scrm客户">
                <div class="title">
                    <el-switch v-model="settingProForm.auto_sync" :active-value="1" :inactive-value="2" class="ml-2" />
                    <p class="after">
                        开启后，来自店铺的用户将根据unionid、openid、手机号自动匹配SCRM客户，如果匹配不上，有手机号的用户将自动创建新的SCRM客户，并按规则分配员工跟进。
                    </p>
                </div>
            </el-form-item>
            <el-form-item label="客户公海" prop="cust_seas_id">
                <el-select v-model="settingProForm.cust_seas_id" placeholder="请选择客户公海">
                    <el-option v-for="item in seas_ids" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="客户来源" prop="cust_source_id">
                <div class="custSource">
                    <el-select v-model="settingProForm.cust_source_id" placeholder="请选择客户来源">
                        <el-option v-for="item in source_ids" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <div class="tips">
                        还没有？
                        <span @click="toAdd">去添加</span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="客户阶段" prop="cust_stage_id">
                <el-select v-model="settingProForm.cust_stage_id" placeholder="请选择客户阶段">
                    <el-option v-for="item in stage_ids" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="分配员工" prop="dist_work_users">
                <select-depart
                    v-model="settingProForm.dist_work_users"
                    :creators="settingProForm.dist_work_users_creators"
                    multiple />
            </el-form-item>
            <el-form-item label="分配方式">
                <el-radio-group v-model="settingProForm.dist_type">
                    <el-radio :label="1"> 随机分配 </el-radio>
                    <el-radio :label="2"> 平均分配 </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="客户标签" prop="cust_tags">
                <select-label
                    v-model="settingProForm.cust_tags"
                    :creators="settingProForm.cust_tags_creators"
                    multiple />
            </el-form-item>
        </el-form>
    </Dialog>

    <!-- 高级同步 -->
    <Dialog :app-dialog="appDialogSynchronousPro">
        <el-form
            ref="synchronousProFormRef"
            :model="synchronousProForm"
            :rules="synchronousProFormRules"
            label-width="auto">
            <el-form-item label="归属店铺" prop="external_shop_id">
                <select-store v-model="synchronousProForm.external_shop_id" @change="changeStore" />
            </el-form-item>
            <el-form-item label="创建时间" prop="created_at">
                <el-date-picker
                    v-model="synchronousProForm.created_at"
                    :editable="false"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    range-separator="—"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    prefix-icon="Calendar"
                    size="small"
                    :disabled-date="disabledDate"
                    @calendar-change="handleChange"
                    @focus="handleFocus" />
                <div style="font-size: 12px">最多选择{{ impose }}天的数据</div>
            </el-form-item>
        </el-form>
    </Dialog>

    <ZWDepart ref="DepartRef" :type="1" @submit="getDepart"></ZWDepart>
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElButton, ElPopper } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import { getCustomerOpenseaSelect } from '@/api/customer/manage/list';
import { sourceList } from '@/view/customer/manage/configure/api';
import { stageList } from '@/api/customerCenter/labellagroup';
import { getStoreSourceList, getDictEnum } from '@/api/ecommerce/storeManage';
import { getOrderList } from '@/api/ecommerce/tradingManage';
import {
    getUserList,
    settingProfessional,
    syncUser,
    exportUserData,
    getAdvancedSetting,
    batchAssignStaff
} from '@/api/ecommerce/userManage';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZWTable from '@/components/zw/table/Table';
import ZWDepart from '@/components/ZWDepart.vue';

import selectDepart from '@/components/customerCenter/selectDepart.vue';
import tableHeaderTooltip from '../../components/tableHeaderTooltip.vue';

import addressPopover from '../../components/addressPopover.vue';
import selectStore from '../../components/selectStore.vue';
import selectLabel from '../../components/selectLabel.vue';

import lodash from 'lodash';
import { deepCopy } from '@/utils/helper';
import router from '@/router';
import { div } from '@/utils/math';
import { downloadFile } from '@/utils/utils';

import dayjs from 'dayjs';

const orderTableRef = ref<HTMLElement | null>(null);
const defaultParams = {};
const tips = ref<string>('删除后，该店铺数据将不能同步，店铺关联的数据也会清除，您确定要删除该店铺吗？');
const synchronousUserTips = ref<string>('同一店铺中，购买账号相同时，将不再同步');
const synchronousTips = ref<string>('同步所有店铺最近180天数据');
const synchronousProTips = ref<string>('同步选择指定店铺指定时间段的数据');
const settingProFormRef = ref<FormInstance>();
const synchronousProFormRef = ref<FormInstance>();
const DepartRef = ref<any>(null);

const pickDay = ref();
const impose = ref(180);

const updateTime = ref<string>('');

const checkList = ref<any>([]);
const checkListSign = ref<any>([]);
let paramsSearch = reactive<any>(null);

const seas_ids = reactive<any>([]);
const source_ids = reactive<any>([]);
const stage_ids = reactive<any>([]);

const isShowRefresh = ref<boolean>(false);

const user_id_tips = ref<any[]>([
    {
        id: 1,
        text: '客易达用户唯一标识'
    }
]);
const account_tips = ref<any[]>([
    {
        id: 1,
        text: '购买平台中客户的唯一标识'
    }
]);
const mobile_tips = ref<any[]>([
    {
        id: 1,
        text: '1. 客易达、自营、有赞订单：订单下单人授权的手机号。'
    },
    {
        id: 2,
        text: '2. 淘宝、天猫、京东、抖店、视频号小店订单：订单收件人的手机号。'
    }
]);
const cust_tips = ref<any[]>([
    {
        id: 1,
        text: '绑定客易达客户信息'
    },
    {
        id: 2,
        text: '1. 客易达、自营、有赞、视频号小店订单：通过订单下单人ID关联系统中的客户。'
    },
    {
        id: 3,
        text: '2. 京东、抖店、快手小店订单：通过订单收件人手机号关联系统中的客户。'
    },
    {
        id: 4,
        text: '3. 淘宝、天猫订单：通过订单收件人手机号/虚拟号服务关联系统中的客户。'
    }
]);

type stateType = {
    searchParams: any;
    deleteId: number | string;
};
const state = reactive<stateType>({
    searchParams: lodash.cloneDeep(defaultParams),
    deleteId: ''
});

type settingProFormType = {
    sync_type?: string | number;
    auto_sync?: string | number;
    cust_seas_id?: string | number;
    cust_source_id?: string | number;
    cust_stage_id?: string | number;
    dist_work_users: any[];
    dist_work_users_creators: any[];
    dist_type?: string | number;
    cust_tags?: [];
    cust_tags_creators?: [];
};
const settingProForm = reactive<settingProFormType>({
    sync_type: 1,
    auto_sync: 2,
    cust_seas_id: '',
    cust_source_id: '',
    cust_stage_id: '',
    dist_work_users: [],
    dist_work_users_creators: [],
    dist_type: 1,
    cust_tags: [],
    cust_tags_creators: []
});
const settingProFormRules = reactive<FormRules>({
    cust_seas_id: [{ required: true, message: '请选择客户公海', trigger: 'change' }],
    cust_source_id: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
    cust_stage_id: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
    dist_work_users: [{ required: true, message: '请选择分配员工', trigger: 'change' }],
    cust_tags: [{ required: true, message: '请选择客户标签', trigger: 'change' }]
});

// 高级同步
type synchronousProFormType = {
    external_shop_id?: string | number;
    created_at: string[];
};
const synchronousProForm = reactive<synchronousProFormType>({
    external_shop_id: '',
    created_at: []
});
const synchronousProFormRules = reactive<FormRules>({
    external_shop_id: [{ required: true, message: '请选择归属店铺', trigger: 'change' }],
    created_at: [{ required: true, message: '请选择下单时间', trigger: 'change' }]
});

const searchOption = computed(() => {
    return [
        {
            label: '店铺类型',
            name: 'retail_shop_type',
            value: '',
            type: 'select',
            placeholder: '请选择店铺类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getDictEnum(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '归属店铺',
            name: 'retail_shop_keyword',
            value: '',
            type: 'input',
            placeholder: '请输入店铺ID｜名称搜索'
        },
        {
            label: '购买账号',
            name: 'external_account',
            value: '',
            type: 'input',
            placeholder: '请输入账号｜手机号搜索'
        },
        {
            label: '绑定客户',
            name: 'cust_keyword',
            value: '',
            type: 'input',
            placeholder: '请输入账号｜手机号搜索'
        },
        {
            label: '归属员工',
            name: 'work_user_id',
            value: '',
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '关联门店',
            name: 'store_code',
            value: '',
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isShopSelect: true,
            formatOption: (v: any) => ({
                label: v.store_name,
                value: v.id
            })
        },

        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '更新时间',
            name: 'updated_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '授权手机',
            name: 'is_virtual_mobile',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { label: '不限制', value: -1 },
                        { label: '正常手机号', value: 1 },
                        { label: '虚拟号', value: 2 }
                    ]);
                });
            }
        }
    ];
});

const tableOption = [
    {
        prop: 'id',
        label: '用户ID',
        width: 140,
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="用户ID" content={user_id_tips.value} />;
        }
    },
    {
        prop: 'shop',
        label: '店铺类型',
        width: 180,
        render({ row }: any) {
            return (
                <div>
                    <span vShow={row.shop.length > 1 || row.shop.length == 0}>--</span>
                    <span vShow={row.shop.length <= 1}>{row.shop[0]?.shop_type_name}</span>
                </div>
            );
        }
    },
    {
        prop: 'shop',
        label: '用户归属店铺',
        width: 200,
        render({ row }: any) {
            return (
                <div>
                    <span vShow={row.shop.length > 1 || row.shop.length == 0}>--</span>
                    <span vShow={row.shop.length <= 1}>{row.shop[0]?.name}</span>
                </div>
            );
        }
    },
    {
        prop: 'external_account',
        label: '购买账号',
        width: 200,
        showOverflowTooltip: true,
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="购买账号" content={account_tips.value} />;
        }
    },
    {
        prop: 'mobile',
        label: '授权手机号',
        width: 240,
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="授权手机号" content={mobile_tips.value} />;
        },
        render({ row }: any) {
            const { mobile, virtual_mobile, is_consignee_mobile } = row;

            if (!mobile && !virtual_mobile) return <div>--</div>;
            return (
                <div>
                    {mobile ? mobile : row.virtual_mobile + '(虚拟号)'}
                    {is_consignee_mobile ? '(收件人)' : ''}
                </div>
            );
        }
    },
    {
        prop: 'cust',
        label: '绑定客户',
        width: 200,
        render({ row }: any) {
            if (row?.cust?.id) {
                const {
                    cust: { id, name, mobile, type: type = 1 }
                } = row;
                return (
                    <div
                        class="bindCust"
                        onClick={() => {
                            const url = `/customer/manage/list/detail?id=${id}&type=${type}`;
                            window.open(url, '_blank');
                        }}>
                        <span>{`${name ?? ''}${mobile ? '(' + mobile + ')' : ''}`}</span>
                    </div>
                );
            } else {
                return '--';
            }
        },
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="绑定客户" content={cust_tips.value} />;
        }
    },
    {
        prop: 'address_list',
        label: '收货人信息',
        width: 260,
        render({ row }: any) {
            const { address_list: address_list = [] } = row;
            if (address_list.length == 1) {
                const { contact, address, region, mobile } = address_list[0];
                return (
                    <div>
                        <div>{`${contact || ''}${mobile ? '-' + mobile + '-' : ''}`}</div>
                        <div>{region + address}</div>
                    </div>
                );
            } else if (address_list.length > 1) {
                return <tableTooltip class="tableTip" content={address_list} />;
            } else {
                return '--';
            }
        }
    },
    {
        prop: 'dist_work_user',
        label: '归属员工',
        width: 160,
        render({ row }: any) {
            return row?.dist_work_user?.name ?? '--';
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        minWidth: 200
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        minWidth: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 160,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }: any) {
            if (row?.cust?.id) {
                return (
                    <ElButton
                        size="small"
                        onClick={() => {
                            checkListSign.value = [row?.cust?.id ?? ''];
                            DepartRef.value.multiple = false;
                            DepartRef.value.departVisble = true;
                        }}>
                        {row?.dist_work_user ? '重新分配' : '分配'}
                    </ElButton>
                );
            } else {
                return '--';
            }
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const expandSearch = () => {
    nextTick(() => {
        orderTableRef.value.getTableH();
    });
};

const disabledDate = (time: number) => {
    if (!pickDay.value) {
        return false;
    }
    if (impose.value) {
        const con1 = new Date(pickDay.value).getTime() - impose.value * 24 * 60 * 60 * 1000;
        const con2 = new Date(pickDay.value).getTime() + impose.value * 24 * 60 * 60 * 1000;
        return time < con1 || time > con2;
    }
    return false;
};
const handleChange = (val: Date[]) => {
    if (impose.value) {
        const [pointDay] = val;
        pickDay.value = pointDay;
    }
};
const handleFocus = () => {
    pickDay.value = null;
};

const changeStore = (value: any) => {
    if (value?.length && value[0].source == 2) {
        impose.value = 90;
    }
    synchronousProFormRef.value.validateField('external_shop_id');
};

const inputSearch = (val: any) => {
    paramsSearch = val;
};
const search = (data: any): void => {
    orderTableRef.value?.clearSelection();
    state.searchParams = data;
};
const reset = (): void => {
    orderTableRef.value?.clearSelection();
    state.searchParams = lodash.cloneDeep(defaultParams);
};
const fetchApi = (): any => {
    return new Promise((resolve: any): any => {
        const page_size: string | number = 15;
        const params = {};
        resolve([params, getUserList]);
    });
};

const toAdd = () => {
    router.push('/customer/manage/configure');
};

const synchronousData = async () => {
    const params = { sync_type: 1 };
    if (await syncUser(params)) {
        isShowRefresh.value = true;
        ElMessage.success('同步成功');
        state.searchParams = { ...state.searchParams };
    }
};
const synchronousProData = () => {
    appDialogSynchronousPro.visible = true;
};

const cancelHandel = (): void => {
    appDialogSettingPro.visible = false;
    settingProForm.auto_sync = 2;
    settingProForm.cust_seas_id = '';
    settingProForm.cust_source_id = '';
    settingProForm.cust_stage_id = '';
    settingProForm.dist_work_users = [];
    settingProForm.dist_work_users_creators = [];
    settingProForm.dist_type = 1;
    settingProForm.cust_tags = [];
    settingProForm.cust_tags_creators = [];
};
const submitHandel = async () => {
    if (!settingProFormRef.value) return;
    await settingProFormRef.value.validate((valid: any): void => {
        if (valid) {
            settingProfessional(settingProForm).then(() => {
                ElMessage.success('设置成功');
                cancelHandel();
                state.searchParams = { ...state.searchParams };
            });
        }
    });
};
const appDialogSettingPro = reactive<any>({
    visible: false,
    title: '高级设置',
    width: '680px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

// 高级同步
const cancelHandelSynchronousPro = (): void => {
    appDialogSynchronousPro.visible = false;
};
const submitHandelSynchronousPro = async () => {
    if (!synchronousProFormRef.value) return;
    await synchronousProFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            let params = lodash.cloneDeep(synchronousProForm);
            params = Object.assign({}, params, { sync_type: 2 });
            params.created_at[1] = dayjs(params.created_at[1]).format('YYYY-MM-DD') + ' 23:59:59';
            // params.sync_type = 2
            // const res = await syncUser(params)
            if (await syncUser(params)) {
                isShowRefresh.value = true;
                ElMessage.success('同步成功');
                appDialogSynchronousPro.visible = false;
                state.searchParams = { ...state.searchParams };
            }
        }
    });
};
const appDialogSynchronousPro = reactive<any>({
    visible: false,
    title: '高级同步',
    width: '600px',
    cancel: cancelHandelSynchronousPro,
    submit: submitHandelSynchronousPro,
    cancelText: '取消',
    submitText: '确定'
});

// 选中表格 checkbox
const onSelect = (selection: any, row: any) => {
    checkList.value = selection;
};
// 全选
const onSelectAll = (selection: any) => {
    checkList.value = selection;
};
const tableDataChange = (data: any): void => {
    updateTime.value = data.last_sync_time;
};

const getSeaList = () => {
    seas_ids.splice(0);
    getCustomerOpenseaSelect({ type: 1 }).then((res: any) => {
        seas_ids.push(...res);
    });
};
const getSourceList = () => {
    source_ids.splice(0);
    sourceList({ page: 1, page_size: 99 }).then((res: any) => {
        source_ids.push(...res.data);
    });
};
const getStageList = () => {
    stage_ids.splice(0);
    stageList({ page: 1, page_size: 99 }).then((res: any) => {
        stage_ids.push(...res);
    });
};

const settingPro = async (): Promise<void> => {
    const params = { sync_type: 1 };
    const res = await getAdvancedSetting(params);
    if (!res) {
        settingProForm.auto_sync = 2;
    } else {
        const {
            auto_sync: auto_sync = 2,
            cust_seas_id: cust_seas_id = '',
            cust_source_id: cust_source_id = '',
            cust_stage_id: cust_stage_id = '',
            dist_type: dist_type = 1,
            dist_work_users: dist_work_users_creators = [],
            cust_tags: cust_tags_creators = []
        } = res;
        settingProForm.auto_sync = auto_sync;
        settingProForm.cust_seas_id = cust_seas_id;
        settingProForm.cust_source_id = cust_source_id;
        settingProForm.cust_stage_id = cust_stage_id;
        settingProForm.dist_type = dist_type;
        settingProForm.dist_work_users_creators = dist_work_users_creators;
        settingProForm.cust_tags_creators = cust_tags_creators;
    }
    appDialogSettingPro.visible = true;
};
const exportSome = async (): Promise<void> => {
    if (checkList.value.length) {
        const extra = { export_type: 1, user_ids: checkList.value.map((ite: any) => ite?.id) };
        const params = Object.assign({}, paramsSearch, extra);
        const { url: href = '' } = await exportUserData(params);
        if (href) {
            downloadFile(href);
            ElMessage.success('导出成功');
        }
    }
};
const exportAll = async (): Promise<void> => {
    const extra = { export_type: 2 };
    const params = Object.assign({}, paramsSearch, extra);
    const { url: href = '' } = await exportUserData(params);
    if (href) {
        downloadFile(href);
        ElMessage.success('导出成功');
    }
};

const getDepart = async (res: any, flag: boolean): Promise<void> => {
    if (!flag) {
        if (res?.length) {
            let customer_list: any[] = [];
            if (DepartRef.value.multiple) {
                customer_list = checkList.value.map((ite: any) => ite?.cust?.id ?? '');
            } else {
                customer_list = checkListSign.value;
            }
            const work_user_list = res.map((item: any) => item.id);
            const params = { customer_list, work_user_list };
            if (await batchAssignStaff(params)) {
                DepartRef.value.selectedMember = [];
                ElMessage.success('分配成功');
                DepartRef.value.departVisble = false;
                state.searchParams = { ...state.searchParams };
            }
        }
    }
};
const exportDistribution = () => {
    if (checkList.value.length) {
        DepartRef.value.multiple = true;
        DepartRef.value.departVisble = true;
    }
};

onMounted(() => {
    getSeaList();
    getSourceList();
    getStageList();
});
</script>

<style lang="scss" scoped>
.user_list_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.title {
    display: flex;
    align-items: flex-start;

    .after {
        margin-top: 4px;
        padding-left: 6px;
        line-height: 1.5;
    }
}

.custSource {
    display: flex;
    align-items: center;

    .tips {
        margin-left: 10px;

        span {
            color: #ff6b00;

            &:hover {
                cursor: pointer;
            }
        }
    }
}

:deep(.bindCust) {
    display: flex;
    align-items: center;
    color: #ff6b00;
    cursor: pointer;
}
</style>
